package com.card.aop;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.View;

import com.card.auth.TokenFilter;
import com.card.auth.TokenUtil;
import com.card.result.Result;

/**
 * ClassName: ResourceAuditAspect <br/>
 * Function: ResourceAuditAspect. <br/>
 * date: 2018年12月10日 下午4:29:28 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Component
@Aspect
public class TokenValidAspect {

	@Pointcut("@annotation(TokenValid)")
	public void tokenValidAspect() {

	}

	@Around("tokenValidAspect()")
	public Object operationAsp(ProceedingJoinPoint jp) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String token = request.getHeader(TokenFilter.AUTH_KEY);
		NativeWebRequest nativeWebRequest = new ServletWebRequest(request);
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) nativeWebRequest.getAttribute(View.PATH_VARIABLES,
				RequestAttributes.SCOPE_REQUEST);
		if (map != null && !map.isEmpty()) {
			int userId = Integer.valueOf(String.valueOf(map.get("userId")));
			if (!TokenUtil.tokenIsValid(userId, token)) {
				return Result.fail(Result.AUTH_ERROR, "token is not valid");
			}
		}
		return jp.proceed();
	}

}
